package com.cxx.purchasecharge.component.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.LineChartDataBean;
import com.cxx.purchasecharge.core.model.AccountingModeCode;
import com.cxx.purchasecharge.core.model.OrderStatusCode;
import com.cxx.purchasecharge.core.model.OrderTypeCode;
import com.cxx.purchasecharge.core.model.persistence.Accounting;
import com.cxx.purchasecharge.core.model.persistence.Order;
import com.cxx.purchasecharge.core.util.DateUtils;
import com.cxx.purchasecharge.dal.AccountingDao;
import com.cxx.purchasecharge.dal.OrderDao;

@Controller
@RequestMapping ("/reportIndex")
public class ReportIndexManager
{
    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger (ReportIndexManager.class);

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AccountingDao accountingDao;

    @RequestMapping (value = "/")
    public String redirectToMainView (ModelMap model)
    {
        return "reportIndex";
    }

    @RequestMapping (value = "/generateLineForOrderVolumePerMonth", method = RequestMethod.POST)
    public @ResponseBody
    String generateLineForOrderVolumePerMonth ()
    {
        Calendar c = Calendar.getInstance ();
        int nowYear = c.get(Calendar.YEAR);
        int nowMonth = c.get(Calendar.MONTH);
        
        LineChartDataBean lineDataBean = new LineChartDataBean ();
        lineDataBean.setName (nowYear + "");
        float[] monthTotal = new float[nowMonth+1];
        for(int month = 0; month < nowMonth+1; month ++) 
        {
            float total = 0;
            Date[] dateRange = getDateRange(nowYear, month);
            List <Order> orderOutFinishedList = orderDao.findByRangeCreateDate(OrderTypeCode.OUT, OrderStatusCode.FINISHED, dateRange[0], dateRange[1]);
            for(Order order : orderOutFinishedList) 
            {
                //total += order.getReceivable();
                total += order.getDealMoney ();
            }
            
            List <Order> orderOutReturnedList = orderDao.findByRangeCreateDate(OrderTypeCode.OUT_RETURN, OrderStatusCode.FINISHED, dateRange[0], dateRange[1]);
            for(Order order : orderOutReturnedList) 
            {
                //total -= order.getReceivable();
                total -= order.getDealMoney ();
            }
            monthTotal[month] = total;
        }
        lineDataBean.setData (monthTotal);
        
        JSONArray json = JSONArray.fromObject(lineDataBean);
        return json.toString();
    }
    
    @RequestMapping (value = "/generateLineForOrderProfitPerMonth", method = RequestMethod.POST)
    public @ResponseBody
    String generateLineForOrderProfitPerMonth ()
    {
        Calendar c = Calendar.getInstance ();
        int nowYear = c.get(Calendar.YEAR);
        int nowMonth = c.get(Calendar.MONTH);
        
        LineChartDataBean lineDataBean = new LineChartDataBean ();
        lineDataBean.setName (nowYear + "");
        float[] monthTotal = new float[nowMonth+1];
        for(int month = 0; month < nowMonth+1; month ++) 
        {
            float total = 0;
            Date[] dateRange = getDateRange(nowYear, month);
            List <Order> orderOutFinishedList = orderDao.findByRangeCreateDate(OrderTypeCode.OUT, OrderStatusCode.FINISHED, dateRange[0], dateRange[1]);
            for(Order order : orderOutFinishedList) 
            {
                total += order.getProfit ();
            }
            
            List <Order> orderOutReturnedList = orderDao.findByRangeCreateDate(OrderTypeCode.OUT_RETURN, OrderStatusCode.FINISHED, dateRange[0], dateRange[1]);
            for(Order order : orderOutReturnedList) 
            {
                total -= order.getProfit();
            }
            
            List<Accounting> accountings = accountingDao.findByTimeRange (dateRange[0], dateRange[1]);
            for(Accounting accounting : accountings) 
            {
                if(AccountingModeCode.IN_COME.equals (accounting.getType ().getAccountingMode ())) 
                {
                    total += accounting.getMoney ();
                } 
                else if(AccountingModeCode.OUT_LAY.equals (accounting.getType ().getAccountingMode ())) 
                {
                    total -= accounting.getMoney ();
                }
            }
            monthTotal[month] = total;
        }
        lineDataBean.setData (monthTotal);
        
        JSONArray json = JSONArray.fromObject(lineDataBean);
        return json.toString();
    }
    
    private Date[] getDateRange(int year, int month) 
    {
        Date[] dateRange = new Date[2]; 
        if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11) 
        {
            dateRange[0] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "01 00:00:00", DateUtils.DATE_TIME_PATTERN);
            dateRange[1] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "31 23:59:59", DateUtils.DATE_TIME_PATTERN);
        }
        else if(month == 3 || month == 5 || month == 8 || month == 10) 
        {
            dateRange[0] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "01 00:00:00", DateUtils.DATE_TIME_PATTERN);
            dateRange[1] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "30 23:59:59", DateUtils.DATE_TIME_PATTERN);
        }
        else 
        {
            if(((GregorianCalendar)Calendar.getInstance ()).isLeapYear (year)) 
            {
                dateRange[0] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "01 00:00:00", DateUtils.DATE_TIME_PATTERN);
                dateRange[1] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "29 23:59:59", DateUtils.DATE_TIME_PATTERN);
            }
            else 
            {
                dateRange[0] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "01 00:00:00", DateUtils.DATE_TIME_PATTERN);
                dateRange[1] = DateUtils.string2Date(year + "-" + (month+1) + "-" + "28 23:59:59", DateUtils.DATE_TIME_PATTERN);
            }
        }
        return dateRange;
    }
}
